package com.shiku.imserver.hander;


import com.shiku.imserver.common.ImSessionContext;
import java.nio.ByteBuffer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.core.GroupContext;
import org.tio.core.exception.AioDecodeException;
import org.tio.core.intf.Packet;
import org.tio.server.intf.ServerAioHandler;

public class ImServerHandler implements ServerAioHandler {
	 private static Logger log = LoggerFactory.getLogger(ImServerHandler.class);
    public void handler(Packet packet, ChannelContext channelContext) throws Exception {
    	log.info("[ww]:ImServerHandler handler");
        AbstractProtocolHandler handler = (AbstractProtocolHandler) ((ImSessionContext) channelContext.getAttribute()).getProtocolHandler();
        if (handler != null) {
            handler.handler(packet, channelContext);
        }
    }

    public ByteBuffer encode(Packet packet, GroupContext groupContext, ChannelContext channelContext) {
        AbstractProtocolHandler handler = (AbstractProtocolHandler) ((ImSessionContext) channelContext.getAttribute()).getProtocolHandler();
        if (handler != null) {
            return handler.encode(packet, groupContext, channelContext);
        }
        return null;
    }

    public Packet decode(ByteBuffer buffer, int limit, int position, int readableLength, ChannelContext channelContext) throws AioDecodeException {
        AbstractProtocolHandler handler = (AbstractProtocolHandler) ((ImSessionContext) channelContext.getAttribute()).getProtocolHandler();
        if (handler != null) {
            return handler.decode(buffer, limit, position, readableLength, channelContext);
        }
        throw new AioDecodeException("不支持的协议类型,无法找到对应的协议解码器!");
    }
}
